package com.kvest.sqlitetest;

import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.kvest.sqlitetest.adapter.DynamicCursorAdapter;
import com.kvest.sqlitetest.contentprovider.ProductContentProvider;
import com.kvest.sqlitetest.datastorage.sqlitestorage.table.ProductTable;
import com.kvest.sqlitetest.fragment.CustomListFragment;

public class CursorLoaderListActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor>,
                                                                          DynamicCursorAdapter.LoadMoreListener {
    private static  final int LOAD_PRODUCTS = 0;

    private boolean isLoading = false;
    private Handler handler = new Handler();
    private boolean repeat;
    private String lastInserted = "0";

    private CustomListFragment fragmentList;
    private DynamicCursorAdapter adapter;

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.fragment_list_layout);

        fragmentList = new CustomListFragment();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        try {
            transaction.add(R.id.list_container ,fragmentList, null);
        } finally {
            transaction.commit();
        }

        initAdapter();

        fragmentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                showAndUpdate(l);
            }
        });

        fragmentList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                Uri deleteUri = Uri.withAppendedPath(ProductContentProvider.ProductContentProviderMetadata.PRODUCTS_URI, Long.toString(l));

                int deleteCount = getContentResolver().delete(deleteUri, null, null);

                Toast.makeText(CursorLoaderListActivity.this, "deleted=" + deleteCount, Toast.LENGTH_LONG).show();

                return true;
            }
        });

        getSupportLoaderManager().initLoader(LOAD_PRODUCTS, null, this);
    }

    public void showAndUpdate(long id) {
        //get and show item
        Uri itemUri = Uri.withAppendedPath(ProductContentProvider.ProductContentProviderMetadata.PRODUCTS_URI,
                Long.toString(id));
        Cursor cursor = getContentResolver().query(itemUri, new String[]{ProductTable.NAME_COLUMN, ProductTable.PID_COLUMN},
                null,null,null);
        cursor.moveToFirst();
        String name = cursor.getString(0);
        int pid = cursor.getInt(1);
        cursor.close();

        Toast.makeText(CursorLoaderListActivity.this, "name=" + name + " pid=" + pid, Toast.LENGTH_SHORT).show();

        //update item
        ContentValues values = new ContentValues(1);
        values.put(ProductTable.PID_COLUMN, pid + 1);
        Log.d("KVEST_TAG", "updatedCount=" + getContentResolver().update(itemUri, values,
                ProductTable.PID_COLUMN + " < ?", new String[]{"15"}));
    }

    @Override
    public void onStart() {
        super.onStart();

        repeat = true;
        Runnable action = new Runnable() {
            @Override
            public void run() {
                repeatedAction();
                if (repeat) {
                    handler.postDelayed(this, 2000);
                }
            }
        };
        handler.postDelayed(action, 2000);
    }

    @Override
    public void onPause() {
        super.onPause();
        repeat = false;
    }

    private void repeatedAction() {
        Log.d("KVEST_TAG", "repeatedAction");

        if ((System.currentTimeMillis() % 2) == 0) {
            ContentValues values = new ContentValues(2);
            values.put(ProductTable.NAME_COLUMN, "Продукт " + System.currentTimeMillis());
            values.put(ProductTable.PID_COLUMN, 17);
            Uri newItem = getContentResolver().insert(ProductContentProvider.ProductContentProviderMetadata.PRODUCTS_URI, values);
            lastInserted = newItem.getLastPathSegment();
        } else {
            Uri deleteUri = Uri.withAppendedPath(ProductContentProvider.ProductContentProviderMetadata.PRODUCTS_URI, lastInserted);
            Log.d("KVEST_TAG", "deleted=" + getContentResolver().delete(deleteUri, null, null));
        }
    }

    private void initAdapter() {
        adapter = new DynamicCursorAdapter(this, R.layout.product_item, null,
                new String[]{ProductTable.NAME_COLUMN, ProductTable.PID_COLUMN},
                new int[]{R.id.product_name_tv, R.id.product_pid_tv}, this);
        fragmentList.setListAdapter(adapter);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
        Log.d("KVEST_TAG", "onCreateLoader[" + id + "]");
        if (id == LOAD_PRODUCTS) {
            CursorLoader cursorLoader = new CursorLoader(this, ProductContentProvider.ProductContentProviderMetadata.PRODUCTS_URI,
                                                         new String[]{ProductTable._ID, ProductTable.NAME_COLUMN, ProductTable.PID_COLUMN},
                                                         null, null, null);
            return cursorLoader;
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        Log.d("KVEST_TAG", "onLoadFinished");
        adapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        Log.d("KVEST_TAG", "onLoaderReset");
        adapter.swapCursor(null);
    }

    @Override
    public void loadMore() {
        if (isLoading) {
            return;
        }

        isLoading = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ie) {}
                for (int i = 0; i < 20; ++i) {
                    ContentValues values = new ContentValues(2);
                    values.put(ProductTable.NAME_COLUMN, "new item " + System.currentTimeMillis());
                    values.put(ProductTable.PID_COLUMN, 7);
                    Log.d("KVEST_TAG", getContentResolver().insert(ProductContentProvider.ProductContentProviderMetadata.PRODUCTS_URI,
                            values).toString());
                }

                isLoading = false;
            }
        }).start();
    }
}
